#include "Socket.hpp"
#include <iostream>
#include <memory>
#include <sys/wait.h>
#include <functional>

using namespace SocketModule;
using namespace LogModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket> &sock, InetAddr &client)>;

class TcpServer
{
public:
    TcpServer(uint16_t port)
        :_port(port)
        ,_listensockptr(std::make_unique<TcpSocket>())
        ,_isrunning(false)
    {
        _listensockptr->BuildTcpSocketMethod(_port);
    }
    void Start(ioservice_t callback)
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr client;
            auto sock = _listensockptr->Accept(&client);
            if (sock == nullptr)
                continue;
            LOG(LogLevel::DEBUG) << "accept success ..." << client.StringAddr();

            pid_t id = fork();
            if (id > 0)
            {
                // 父进程
                sock->Close();
                pid_t rid = ::waitpid(id, nullptr, 0);
            }
            else if (id == 0)
            {
                // 子进程
                _listensockptr->Close();
                if (fork() > 0) // 让孙子进程去调用函数，子进程退出，使孙子进程变成孤儿进程从而不需要手动回收
                    exit(OK);
                callback(sock, client);
                sock->Close();
                exit(OK);
            }
            else
            {
                LOG(LogLevel::FATAL) << "fork error ...";
                exit(FORK_ERR);
            }
        }
        _isrunning = false;
    }
    ~TcpServer() 
    {}
private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;
    bool _isrunning;
};